<?php

namespace app\api\controller\live;

use app\api\model\live\LiveAudioEvent;
use app\api\model\live\LiveProduct;
use app\api\model\live\LiveProductAssistText;
use app\api\model\live\LiveProductText;
use app\api\model\live\LiveTips;
use app\api\model\live\LiveUserProduct;
use app\api\model\live\LiveVoice;
use app\api\service\live\EventService;
use app\api\service\token\LoginToken;
use app\lib\exception\live\LiveException;
use LinCmsTp5\admin\model\LinUser;
use think\Request;
use think\Db;
use think\Exception;

class Event
{
    protected $Service;
    public function __construct()
    {
        $this->Service = EventService::getInstance();
    }

    function records(Request $request){
        $params = $request->post();
        $result = $this->Service->records($params);
        return writeJson(200,$result,"导入成功");
    }

    function list(Request $request){
        $params = $request->get();
        $list = $this->Service->list($params);
        return writeJson(200,$list,"获取成功");
    }

    function recapture(Request $request){
        $this->Service->recapture();
        return writeJson(200,[],"重新采集重置完成");
    }

    function getRecapture(Request $request){
        $params = $request->get();
        $result = $this->Service->getRecapture($params);
        return writeJson(200,$result,"重新采集完成");
    }

    function addProducts(Request $request){
        $params = $request->post();
        $result = $this->Service->addProducts($params);
        return writeJson(200,$result,"入库成功");
    }

    public function getProductItem(Request $request)
    {
        $params = $request->get();
        $result = $this->Service->getProductItem($params);
        return writeJson(200,$result,'待处理条目！');
    }

    public function upProductItem(Request $request)
    {
        $params = $request->post();
        $result = $this->Service->upProductItem($params);
        return writeJson(200,$result,'更新成功！');
    }

    public function getProducts(Request $request){
        $params = $request->post();
        $result = $this->Service->getProducts($params);
        return writeJson(200,$result,'数据列表！');
    }

    public function addAudioEvent(Request $request)
    {
        $params = $request->post();
        $create_time = date('Y-m-d 00:00:00',time());
        $uid = LoginToken::getInstance()->getCurrentUid();

        $product = LiveUserProduct::where("uid", $uid)->findOrEmpty();
        if ($product->isEmpty()) {
            return writeJson(400,[],'未分配选品！');
        }
        $info = LiveAudioEvent::where("create_time", ">=", $create_time)
            ->where("status", "<>", 4)
            ->where("uid", $uid)
            ->whereNull("delete_time")
            ->count();
        if ($info > 5) {
            return writeJson(400,[],'今日已领取过音频！');
        }
        $data["uid"] = $uid;
        $data["folder"] = $product["folder"];
        $result = LiveAudioEvent::create($data);
        return writeJson(200,$result,'新增！');
    }

    public function checkAudioEvent(Request $request)
    {
        $params = $request->get();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $info = LiveAudioEvent::field("id,url,status")->where("id", $params["id"])->findOrEmpty();
        return writeJson(200,$info,'成功！');
    }

    public function getAudioEvent(Request $request)
    {
        $info = LiveAudioEvent::where("status", 1)->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->status = 2;
            $info->save();
        } else {
            throw new LiveException([
                'msg' => '无数据',
                'error_code' => 20001
            ]);
        }

        $product = LiveProduct::where("folder", $info["folder"])->findOrEmpty();
        if (!$product->isEmpty()) {
            $info["voice"] = $product["voice"];
            $voice = LiveVoice::where("code", $info["voice"])->findOrEmpty();
            if (!$voice->isEmpty()) {
                $info["ty_folder"] = $voice["ty_folder"];
                $info["front_folder"] = $voice["front_folder"];
            }
        }

        return writeJson(200,$info,'成功！');
    }

    public function backfillAudioEvent(Request $request)
    {
        $params = $request->post();
        $info = LiveAudioEvent::where("id",$params["id"])->findOrEmpty();
        if ($info->isEmpty()) {
            return writeJson(200,$info,'任务不存在！');
        }
        $info->save($params,["id"=>$info['id']]);
        return writeJson(200,$info,'回填成功！');
    }

    public function tipsList(Request $request)
    {
        $uid = LoginToken::getInstance()->getCurrentUid();
        $product = LiveUserProduct::where("uid", $uid)->findOrEmpty();
        $list = LiveTips::where("product_id", $product["product_id"])->select()->toArray();
        return writeJson(200,$list,'成功！');
    }

    /**
     * @param('username','username','require')
     * @param('product_id','product_id','require')
     */
    public function addUser(Request $request)
    {
        $params = $request->get();
        DB::startTrans();
        try {

            $user = LinUser::where("username", $params["username"])->findOrEmpty();
            if (!$user->isEmpty()) {
                throw new Exception( '用户名已存在');
            }

            $user_data = [
                "username"=>$params['username'],
                "nickname"=>$params['username'],
                "password"=>md5('123456'),
                "admin"=>1,
                "active"=>1,
                "group_id"=>4
            ];
            $user = LinUser::create($user_data);
            $data['uid'] = $user['id'];

            $product = LiveProduct::where("id", $params["product_id"])->findOrEmpty();

            $user_product_data = [
                "uid"=>$data["uid"],
                "username"=>$params['username'],
                "product_id"=>$params['product_id'],
                "product"=>$product['name'],
                "folder"=>$product['folder']
            ];
            $user_product = LiveUserProduct::create($user_product_data);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new LiveException([
                'msg' => $e->getMessage(),
                'error_code' => 20001
            ]);
        }
        return writeJson(200,true,'成功！');

    }

    public function getUserProduct(Request $request)
    {
        $params = $request->post();
        $pageSize = $params['pageSize'] ?? 50;

        $query = new LiveUserProduct();
        if (isset($params['username']) && $params['username'] != ""){
            $query = $query->whereLike('username',"%".$params['username']."%");
        }
        if (isset($params['product']) && $params['product'] != ""){
            $query = $query->whereLike('product',"%".$params['product']."%");
        }
        if (isset($params['folder']) && $params['folder'] != ""){
            $query = $query->whereLike('folder',"%".$params['folder']."%");
        }

        $list = $query->where("id", "<>", 413)->where("id", "<>", 360)
            ->order("id", "desc")->paginate($pageSize);

        return writeJson(200,$list,'成功！');

    }

    public function modifyUserName(Request $request)
    {
        $params = $request->post();
        DB::startTrans();
        try {
            $info = LiveUserProduct::where("id", $params["id"])->findOrEmpty();
            $info->username = $params["new"];
            $info->save();

            $user_info = LinUser::where("id", $info["uid"])->findOrEmpty();
            $user_info->nickname = $params["new"];
            $user_info->username = $params["new"];
            $user_info->save();
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new Exception([
                'msg' => "失败",
                'error_code' => 20003
            ]);
        }

        return writeJson(200,"",'成功！');

    }

    public function productList(Request $request)
    {
        $params = $request->get();
        $pageSize = $params['pageSize'] ?? 50;


        $query = new LiveProduct();
        if (isset($params['field']) && $params['field'] != ""){
            $query = $query->field($params['field']);
        }
        if (isset($params['type']) && $params['type'] != ""){
            $query = $query->where('type', $params['type']);
        }
        if (isset($params['platform']) && $params['platform'] != ""){
            $query = $query->where('platform', $params['platform']);
        }
        if (isset($params['name']) && $params['name'] != ""){
            $query = $query->whereLike('name', "%".$params['name']."%");
        }
        if (isset($params['folder']) && $params['folder'] != ""){
            $query = $query->whereLike('folder', "%".$params['folder']."%");
        }
        $list = $query->whereNull('delete_time')->whereNotNull("type")->order("id", "desc")->paginate($pageSize);

        return writeJson(200,$list,'成功！');
    }

    public function getproductList(Request $request)
    {
        $params = $request->get();

        $query = new LiveProduct();
        if (isset($params['field']) && $params['field'] != ""){
            $query = $query->field($params['field']);
        }
        if (isset($params['type']) && $params['type'] != ""){
            $query = $query->where('type', $params['type']);
        }
        if (isset($params['name']) && $params['name'] != ""){
            $query = $query->whereLike('name', "%".$params['name']."%");
        }
        if (isset($params['folder']) && $params['folder'] != ""){
            $query = $query->whereLike('folder', "%".$params['folder']."%");
        }
        $list = $query->whereNull('delete_time')->select()->toArray();

        return writeJson(200,$list,'成功！');
    }

    public function getProductText()
    {
        $result = LiveProductText::with("product")->where('status',1)->findOrEmpty();

        if (!$result->isEmpty()){
            $result->save(["status"=>2], ["id"=>$result['id']]);
        }
        return writeJson(200,$result,'成功！');
    }

    public function backFillText(Request $request)
    {
        $params = $request->post();
        DB::startTrans();
        try {
            $info = LiveProductText::where("id",$params["id"])->where("status", 2)->findOrEmpty();
            if ($info->isEmpty()) {
                throw new Exception([
                    'msg' => "该任务不存在",
                    'error_code' => 20003
                ]);
            }
            $info->save($params,["id"=>$info['id']]);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new Exception([
                'msg' => "回填失败",
                'error_code' => 20003
            ]);
        }
        return writeJson(200,$info,'成功！');

    }

    public function getVoiceList()
    {
        $list = LiveVoice::select()->toArray();
        return writeJson(200,$list,'成功！');
    }

    /**
     * @param('name','name','require')
     * @param('folder','folder','require')
     * @param('voice','voice','require')
     * @param('type','type','require')
     */
    public function addProduct(Request $request)
    {
        $params = $request->post();

        $item = LiveProduct::where("folder", $params["folder"])->findOrEmpty();
        if ($item->isEmpty()) {
            $params["platform"] = "抖音";
            if (strpos($params["folder"], "tb_") != false) {
                $params["platform"] = "淘宝";
            }
            if (strpos($params["folder"], "ks_") != false) {
                $params["platform"] = "快手";
            }
            $res = LiveProduct::create($params);
        } else {
//            if ($params["name"] == $item["name"]) {
//                return writeJson(200,[],'商品名重复！');
//            }
            if ($params["folder"] == $item["folder"]) {
                return writeJson(200,[],'文件名重复！');
            }
        }
        return writeJson(200,$res,'成功！');
    }

    public function importProductText(Request $request){
        $file = $request->file('file');
        $result = $this->Service->importProductText($file);
        return writeJson(200,$result,'完成！');
    }

    public function importTips(Request $request){
        $file = $request->file('file');
        $result = $this->Service->importTips($file);
        return writeJson(200,$result,'完成！');
    }

    public function exportProductText(Request $request)
    {
        $params = $request->get();

        $list = LiveProductText::field("text, voice_type")->where("product_id", $params["product_id"])->select()->toArray();
        $info = LiveProduct::where("id", $params["product_id"])->findOrEmpty();
        if (!empty($list)) {

            $xlsName = date('Ymd')."_".$info["name"]."_话术"; // 表名称
            $xlsCell = [
                ['text', 'text'],
                ['voice_type', 'voice_type']
            ];// 表头信息

            $this->downloadExcel($xlsName, $xlsCell, $list);// 传递参数

        }
    }

    public function downloadExcel($expTitle, $expCellName, $expTableData)
    {
        $xlsTitle    = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $cellNum     = count($expCellName);// 单元格长度
        $dataNum     = count($expTableData);
        $objPHPExcel = new \PHPExcel();// 引入库
        $cellName = [
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
        }

        // Miscellaneous glyphs, UTF-8  循环写入数据
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)
                    ->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");//创建生成的格式
        header('Content-Disposition: attachment;filename="'.$xlsTitle.'.xlsx"');//下载下来的表格名
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        return $PHPWriter->save('php://output');
    }

    /**
     * @param('product_id','product_id','require')
     */
    public function getProductTextList(Request $request)
    {
        $params = $request->post();
        $query = new LiveProductText();
        if (isset($params['keyword']) && $params['keyword'] != ""){
            $query = $query->whereLike('text', "%".$params['keyword']."%");
        }
        $list = $query->where("product_id", $params["product_id"])->select()->toArray();
        return writeJson(200,$list,'完成！');
    }

    /**
     * @param('product_id','product_id','require')
     */
    public function getTipsList(Request $request)
    {
        $params = $request->post();
        $query = new LiveTips();
        if (isset($params['keyword']) && $params['keyword'] != ""){
            $query = $query->whereLike('tip', "%".$params['keyword']."%");
        }
        $list = $query->where("product_id", $params["product_id"])->select()->toArray();
        return writeJson(200,$list,'完成！');
    }

    public function upProductText(Request $request)
    {
        $params = $request->post();
        $event = new LiveProductText();
        $info = $event->where("id", $params["id"])->findOrEmpty();
        if ($info->isEmpty()) {
            return writeJson(200,"",'信息不存在！');
        }
        $info->text = $params["text"];
        $info->status = 1;
        $info->path = Null;
        $info->save();
        return writeJson(200,true,'完成！');
    }

    public function upTips(Request $request)
    {
        $params = $request->post();
        $event = new LiveTips();
        $info = $event->where("id", $params["id"])->findOrEmpty();
        if ($info->isEmpty()) {
            return writeJson(200,"",'信息不存在！');
        }
        $info->tip = $params["tip"];
        $info->save();
        return writeJson(200,true,'完成！');
    }
    /**
     * @param('id','id','require')
     */
    public function deleteUserProduct(Request $request)
    {
        $params = $request->get();
        DB::startTrans();
        try {
            $user_product = new LiveUserProduct();
            $info = $user_product->where("id", $params["id"])->findOrEmpty();
            $res = $user_product->where("id", $params["id"])->delete();
            LinUser::deleteUser($info["uid"]);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return writeJson(200,$res,'成功！');
    }
    /**
     * @param('product_id','product_id','require')
     */
    public function replaceText(Request $request)
    {
        $params = $request->post();
        $event = new LiveProductText();
        $texts = $event->where("product_id", $params["product_id"])->select()->toArray();
        $savedata = [];
        if (!empty($texts)) {
            foreach ($texts as $text) {
                if (strpos($text["text"], $params["keyword"]) !== false) {
                    $item = [];
                    $item["id"] = $text["id"];
                    $item["text"] = str_replace($params["keyword"], $params["replace_word"], $text["text"]);
                    $item["status"] = 1;
                    $item["path"] = Null;
                    $savedata[] = $item;
                }
            }
            $res = $event->saveAll($savedata);
        }
        return writeJson(200,count($res),'完成！');

    }

    /**
     * @param('product_id','product_id','require')
     */
    public function replaceTip(Request $request)
    {
        $params = $request->post();
        $event = new LiveTips();
        $texts = $event->where("product_id", $params["product_id"])->select()->toArray();
        $savedata = [];
        if (!empty($texts)) {
            foreach ($texts as $text) {
                if (strpos($text["tip"], $params["keyword"]) !== false) {
                    $item = [];
                    $item["id"] = $text["id"];
                    $item["tip"] = str_replace($params["keyword"], $params["replace_word"], $text["tip"]);
                    $savedata[] = $item;
                }
            }
            $res = $event->saveAll($savedata);
        }
        return writeJson(200,count($res),'完成！');

    }
    /**
     * @param('id','id','require')
     */
    public function delProduct(Request $request)
    {
        $params = $request->post();
        $current_time = date("Y-m-d H:i:s");

        $event = new LiveProduct();
        $product = $event->where("id", $params["id"])->findOrEmpty();
        $product->delete_time = $current_time;
        $product->save();

        return writeJson(200,True,'完成！');

    }

    public function changeVoice(Request $request)
    {
        $params = $request->get();
        DB::startTrans();
        try {
            $res = LiveProductText::where("product_id", $params["product_id"])
                ->update([
                    "voice_type"=>$params["voice_type"],
                    "status"=>1,
                    "path"=>null
                ]);
            LiveProduct::where("id", $params["product_id"])->update(["voice"=>$params["voice_type"]]);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new LiveException([
                'msg' => "失败",
                'error_code' => 20001
            ]);
        }
        return writeJson(200,True,'完成！');

    }

//    获取助播话术
    public function getAssistText(Request $request)
    {
        $params = $request->get();
        $result = LiveProductAssistText::where('status',1)->findOrEmpty();

        if (!$result->isEmpty()){
            $result->save(["status"=>2], ["id"=>$result['id']]);
        }
        return writeJson(200,$result,'成功！');
    }

    public function backfillAssistText(Request $request)
    {
        $params = $request->post();
        DB::startTrans();
        try {
            $info = LiveProductAssistText::where("id",$params["id"])->where("status", 2)->findOrEmpty();
            if ($info->isEmpty()) {
                throw new Exception([
                    'msg' => "该任务不存在",
                    'error_code' => 20003
                ]);
            }
            $info->save($params,["id"=>$info['id']]);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new Exception([
                'msg' => "回填失败",
                'error_code' => 20003
            ]);
        }
        return writeJson(200,$info,'成功！');

    }
}
